<template>
  <div id="home">
    <!-- 头部 -->
    <div class="home_nav">
      <!-- logo -->
      <img src="../assets/images/homelogo/logo.png" alt="" />
      <!-- 右边栏 下拉选择地址 -->
      <van-popover
        v-model="showPopover"
        trigger="click"
        :actions="actions"
        @select="onSelect"
        placement="bottom-end"
      >
        <template #reference>
          <!-- 地址文本显示 -->
          <span class="address">{{ addresstext }}</span>
          <van-button type="primary">
            <!-- 地址标识 -->
            <van-icon name="location-o" size="28" color="rgb(104, 99, 99)" />
          </van-button>
        </template>
      </van-popover>
    </div>

    <!-- 轮播图 -->
    <van-swipe class="my-swipe" :autoplay="2300" indicator-color="white">
      <van-swipe-item v-for="(item, i) in swipe" :key="i">
        <router-link to="/product">
          <img :src="item.img" alt="" />
        </router-link>
      </van-swipe-item>
    </van-swipe>

    <!-- 会员推荐 -->
    <div class="member">
      <p>
        尊享礼遇享不停，升级aha会员
        <br />
        预计可省￥358+，
        <router-link to="/vip">了解更多</router-link>
      </p>
      <img src="../assets/images/member/ahaRights_1.png" alt="" srcset="" />
      <router-link to="/vip"> 立即开通 ￥99/年 </router-link>
    </div>

    <!-- 0元购 -->
    <div class="discount">
      <!-- 头部 -->
      <div>
        <img src="../assets/images/discount/title.png" alt="" />
        <!-- 跳转 -->
        <router-link to="/product">
          <img src="../assets/images/discount/btn_more.png" alt="" srcset="" />
        </router-link>
      </div>
      <!-- 商品 -->
      <van-grid icon-size="40px" column-num="3" :gutter="6">
        <van-grid-item
          v-for="(item, i) in yuan"
          :key="i"
          :text="`￥${item.cake_price}`"
          :to="`/detail?id=${item.cid}&name=${item.cakename}`"
          :icon="item.cake_pic"
        />
      </van-grid>
    </div>

    <!-- 新人有礼轮播 -->
    <!-- 通用轮播样式 -->
    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item>
        <router-link to="">
          <img src="../../public/images/HomeSwipe/swipe_001.jpg" />
        </router-link>
      </van-swipe-item>
      <van-swipe-item>
        <router-link to="">
          <img src="../../public/images/HomeSwipe/swipe_002.jpg" alt="" />
        </router-link>
      </van-swipe-item>
    </van-swipe>

    <!-- 蛋糕推荐 -->
    <div class="cakeRecommended">
      <p>-&nbsp;蛋糕推荐&nbsp;-</p>
      <div v-for="(item, i) in icon001" :key="i">
        <router-link :to="`/detail?id=${item.cid}&name=${item.cakename}`">
          <img :src="item.img" alt="" />
        </router-link>
        <div>
          <span></span>
          <div>
            <p>{{ item.cakename }}</p>
            <p>{{ item.cake_description }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 企业兑换 -->
    <div class="corporateExchange">
      <van-grid icon-size="25px" column-num="3" :gutter="30">
        <van-grid-item
          v-for="(item, i) in bottomticket"
          :key="i"
          :text="item.name"
          :icon="item.icon"
          @click="jump(item)"
        />
      </van-grid>
    </div>

    <!-- 尾部版权 -->
    <div class="tailCopyright">
      <h3>
        copyright&nbsp;©&nbsp;2010-2021&nbsp;&nbsp;诺心lecake.com版权所有
        <br />
        诺心食品（上海）有限公司&nbsp;&nbsp;沪ICP备10211730号-2
      </h3>
    </div>

    <!-- 底部栏 -->
    <foot></foot>
  </div>
</template>

<script>
import { Toast } from "vant"
import "../untils/location"
export default {
  data() {
    return {
      // 显示地址下拉列表
      showPopover: false,
      // 地址下拉列表文本
      actions: [
        { text: "" },
        { text: "北京市" },
        { text: "上海市" },
        { text: "天津市" },
        { text: "重庆市" },
        { text: "其它" },
      ],
      // 地址呈现
      addresstext: "",
      // 底部会员狂欢
      bottomticket: [
        { icon: "vip-card-o", name: "会员狂欢", to: "/vip" },
        { icon: "coupon-o", name: "卡券兑换", to: "/coupon" },
        { icon: "point-gift-o", name: "积分转盘", to: "/integral" },
      ],
      // 轮播
      swipe: [],
      // 推荐
      icon001: [],
      // 零元购
      yuan: [],
    }
  },
  created() {
    this.getLocation()
    let timer = setInterval(() => {
      this.addresstext = localStorage.getItem("city")
      this.actions[0].text = this.addresstext
      if (this.addresstext != null) {
        clearInterval(timer)
      }
    }, 2000)

    // 轮播图
    this.$get(`/v1/home/swipe`).then(res => {
      this.swipe = res.data.data
    })
    // 0元购商品
    this.$get(`/v1/home/yuan`).then(res => {
      this.yuan = res.data.data
    })
    // 推荐商品
    this.$get(`/v1/home/all`).then(res => {
      this.icon001 = res.data.data
    })
  },
  mounted() {},
  methods: {
    /**获取地图定位*/
    // methods部分
    getLocation() {
      const self = this
      AMap.plugin("AMap.Geolocation", function () {
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000,
        })

        geolocation.getCurrentPosition()
        AMap.event.addListener(geolocation, "complete", onComplete)
        AMap.event.addListener(geolocation, "error", onError)

        function onComplete(data) {
          // data是具体的定位信息
          // console.log('定位成功信息：', data);
          // console.log(data.addressComponent.city);
          localStorage.setItem("city", data.addressComponent.city)
        }

        function onError(data) {
          // 定位出错
          // console.log('定位失败错误：', data);
          // 调用ip定位
          self.getLngLatLocation()
        }
      })
    },
    getLngLatLocation() {
      AMap.plugin("AMap.CitySearch", function () {
        var citySearch = new AMap.CitySearch()
        citySearch.getLocalCity(function (status, result) {
          if (status === "complete" && result.info === "OK") {
            // 查询成功，result即为当前所在城市信息
            // console.log('通过ip获取当前城市：', result.city)
            localStorage.setItem("city", result.city)
            //逆向地理编码
            AMap.plugin("AMap.Geocoder", function () {
              var geocoder = new AMap.Geocoder({
                // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                city: result.adcode,
              })

              var lnglat = result.rectangle.split(";")[0].split(",")
              geocoder.getAddress(lnglat, function (status, data) {
                if (status === "complete" && data.info === "OK") {
                  // result为对应的地理位置详细信息
                  // console.log(data)
                }
              })
            })
          }
        })
      })
    },
    // 点击地址下拉列表
    onSelect(action) {
      Toast(action.text)
      this.addresstext = action.text
    },
    jump(i){
      let token=localStorage.getItem("token");
      if(token==null){
        this.$dialog({
          message: "不好意思您还没有登录吧",
        }).then(() => {
          this.$router.push(`/usercenter`);
        });
      }else{
        let params = { product_id: i, token: token };
        this.$get(`/v1/login/verify`, params).then((res) => {
          if(res.data.msg=="token失效"){
            this.$dialog({
              title: "请重新登录",
              message: "您的登录状态已过期",
            }).then(()=>{
              this.$router.push('/usercenter');
            })
          }else{
            this.$router.push(`${i.to}`)
          }
        });
      }
    },
  },
}
</script>

<style lang="scss">
// home页面
#home {
  // 头部
  .home_nav {
    padding-top: 1rem;
    height: 4.5rem;
    background-color: white;
    // logo标志
    > img {
      height: 2.5rem;
      padding-left: 1.5rem;
    }
    // 地址下拉列表
    .van-popover__wrapper {
      line-height: 2rem;
      display: inline-block;
      position: absolute;
      right: 1rem;
      // 地址按钮
      button {
        border: none;
        width: 2rem;
        background-color: white;
      }
      // 地址文本显示
      .address {
        display: inline-block;
        line-height: 2.75rem;
        padding-right: 0.3125rem;
      }
      .van-icon-location-o {
        margin-bottom: 0.9rem;
      }
    }
  }

  // 轮播图
  > .my-swipe {
    .van-swipe-item {
      img {
        display: block;
        width: 100%;
      }
    }
  }

  // 开通会员
  .member {
    width: 100%;
    height: 13.9375rem;
    background: url("../assets/images/member/ahaPanelBg.jpg") no-repeat;
    background-size: 100%;
    position: relative;
    margin-bottom: 1rem;
    // 会员文字
    > p {
      font-size: 0.9rem;
      font-weight: 300;
      position: absolute;
      bottom: 40%;
      left: 5%;
      > a {
        color: #cea461;
      }
    }
    // 开通
    > a {
      position: absolute;
      bottom: 20%;
      left: 5%;
      display: block;
      padding: 0.4rem 1.4rem;
      background: #cea461;
      color: white;
      font-size: 0.875rem;
    }
    // 右侧图片
    > img {
      height: 75%;
      position: absolute;
      right: 5%;
      top: 13%;
    }
  }

  // 0元购
  .discount {
    background: url("../assets/images/discount/bg.png");
    height: 13rem;
    margin-bottom: 0.7rem;
    > div:first-child {
      position: relative;
      height: 3rem;
      // 左侧logo
      > img {
        width: 40%;
        margin-top: 1rem;
        position: absolute;
        left: 5%;
      }
      // 更多跳转
      > a > img {
        width: 20%;
        margin-top: 0.6rem;
        position: absolute;
        right: 3%;
      }
    }
    // 商品排列
    > .van-grid {
      width: 94%;
      margin: 0 auto;
      [class*="van-hairline"]::after {
        border: none;
      }
      // 单独商品
      > .van-grid-item {
        > .van-grid-item__content {
          padding: 0;
          background: rgba(0, 0, 0, 0);
          // 图片
          .van-icon {
            width: 100%;
            height: 100%;
            .van-icon__image {
              width: 100%;
              height: 100%;
            }
          }
          // 文字
          > .van-grid-item__text {
            display: block;
            width: 96%;
            height: 1.5rem;
            line-height: 1.5rem;
            padding-left: 5%;
            margin: 0 auto;
            background: url("../assets/images/discount/btn_grey.png") no-repeat;
            background-size: 100%;
            color: #866f53;
            text-decoration: line-through;
          }
        }
      }
    }
  }

  // 蛋糕推荐
  .cakeRecommended {
    background: #ffffff;
    padding-top: 1.2rem;
    color: #3e3e3e;
    // 头部文字
    > p {
      display: block;
      text-align: center;
      height: 1rem;
      line-height: 1rem;
      font-weight: bold;
      font-size: 0.9rem;
    }
    // 详情
    > div {
      margin-top: 0.8rem;
      position: relative;
      // 图片
      > a {
        > img {
          width: 100%;
          display: block;
        }
      }
      // 文字块
      > div {
        // 红色块
        > span {
          position: absolute;
          top: 1.6rem;
          left: 3%;
          display: block;
          width: 0.3125rem;
          height: 0.9375rem;
          background: #e8380d;
        }
        // 文字
        > div {
          position: absolute;
          top: 1.4rem;
          left: 6%;
          > p:first-child,
          p:last-child {
            font-weight: 400;
            font-size: 0.9rem;
            line-height: 1.4rem;
            height: 1.4rem;
            margin: 0;
          }
          > p:last-child {
            font-size: 0.7rem;
          }
        }
      }
    }
  }

  // 企业兑换
  .corporateExchange {
    margin-top: 1.3rem;
    background: #ffffff;
    > .van-grid {
      width: 88%;
      margin: 0 auto;
      [class*="van-hairline"]::after {
        border: none;
      }
    }
  }

  // 尾部版权
  .tailCopyright {
    margin-top: 2rem;
    height: 6.8rem;
    > h3 {
      font-size: 0.625rem;
      color: #bababa;
      line-height: 0.9rem;
      font-weight: normal;
      text-align: center;
    }
  }
}
</style>
